package com.example.adminLite.admin.controller;

import com.example.adminLite.exception.WebRunException;
import com.example.adminLite.model.MusicType;
import com.example.adminLite.service.MusicTypeService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("admin/musicType")
public class MusicTypeController {

    private final MusicTypeService musicTypeService;

    public MusicTypeController(MusicTypeService musicTypeService) {
        this.musicTypeService = musicTypeService;
    }

    @GetMapping("add")
    public ModelAndView add(
            @RequestParam(required = false, defaultValue = "") String  errorMessage,
            ModelAndView modelAndView
    ) {
        modelAndView.addObject("errorMessage", errorMessage);
        modelAndView.setViewName("/admin/musicType/add");
        return modelAndView;
    }

    @GetMapping("index")
    public ModelAndView  index(ModelAndView modelAndView) {
        List<MusicType> musicTypeList = this.musicTypeService.index();
        modelAndView.addObject("musicTypeList", musicTypeList);
        modelAndView.setViewName("/admin/musicType/index");
        // System.out.println(musicTypeList);
        return modelAndView;
    }

    @GetMapping("edit")
    public ModelAndView edit(
            @RequestParam long id,
            ModelAndView modelAndView
    ) {
        MusicType musicType = this.musicTypeService.findById(id);
        modelAndView.addObject("musicType", musicType);
        modelAndView.setViewName("/admin/musicType/edit");
        return modelAndView;
    }

    @PostMapping("save")
    public String save(
            @RequestParam(required = false, defaultValue = "0") long id,
            @RequestParam String musicTypeName,
            @RequestParam int musicTypeOrder
    ) {
        MusicType musicType = new MusicType();
        if (id != 0){
            musicType.setId(id);
        }
        musicType.setMusicTypeName(musicTypeName);
        musicType.setMusicTypeOrder(musicTypeOrder);
        this.musicTypeService.save(musicType);

        return "redirect:/admin/musicType/index";
    }

    @GetMapping("del")
    public String del(
            @RequestParam long id
    ) {
        this.musicTypeService.del(id);
        return "redirect:/admin/musicType/index";
    }


}
